import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Badge,
  Form,
  Input,
  Button,
  Table,
  Select,
  Pagination,
  InputNumber,
  Modal,
} from 'antd';

import moment from 'moment';
import styles from './ConfigItemList.less';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

const EditableContext = React.createContext();
const FormItem = Form.Item;
const EditableFormRow = Form.create()(({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
));

// 弹窗增加配置项
const CreateForm = Form.create()(prop => {
  const { modalVisible, form, handleAdd, hideAddModal, groupAllCodeList } = prop;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) {
        return;
      }
      form.resetFields();
      handleAdd(fieldsValue);
    });
  };

  const options = groupAllCodeList.map(d => <Select.Option key={d.value}>{d.text}</Select.Option>);

  return (
    <Modal
      destroyOnClose
      title="新增"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => hideAddModal()}
    >
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 17 }} label="配置组code">
        {form.getFieldDecorator('groupCode', {
          rules: [{ required: true, message: '请选择配置组code！' }],
        })(
          <Select
            showSearch
            placeholder="请选择配置组code"
            optionFilterProp="children"
            filterOption={(input, option) =>
              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
          >
            {options}
          </Select>
        )}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 17 }} label="配置key">
        {form.getFieldDecorator('confKey', {
          rules: [{ required: true, message: '请输入配置key！' }],
        })(<Input placeholder="请输入 confKey" />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 17 }} label="配置值">
        {form.getFieldDecorator('confValue', {
          rules: [{ required: true, message: '请输入配置value！' }],
        })(<Input placeholder="请输入 confValue" />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 17 }} label="备注">
        {form.getFieldDecorator('remark', {
          rules: [{ required: true, message: '配置项描述！' }],
        })(<Input placeholder="请输入 remark" />)}
      </FormItem>
    </Modal>
  );
});

const EditForm = Form.create()(props => {
  const { modalVisible, form, handleEdit, hideEditModal, item } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) {
        return;
      }
      form.resetFields();
      handleEdit(fieldsValue);
    });
  };
  return (
    <Modal
      destroyOnClose
      title="修改"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => hideEditModal()}
    >
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 17 }} label="配置id">
        {form.getFieldDecorator('id', {
          initialValue: item.id,
        })(<Input disabled />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 17 }} label="配置code">
        {form.getFieldDecorator('groupCode', {
          initialValue: item.groupCode,
          rules: [{ required: true, message: '请输入配置code！' }],
        })(<Input placeholder="请输入 groupCode" disabled />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 17 }} label="配置key">
        {form.getFieldDecorator('confKey', {
          initialValue: item.confKey,
          rules: [{ required: true, message: '请输入配置key！' }],
        })(<Input placeholder="请输入 confKey" />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 17 }} label="配置值">
        {form.getFieldDecorator('confValue', {
          initialValue: item.confValue,
          rules: [{ required: true, message: '请输入配置value！' }],
        })(<Input placeholder="请输入 confValue" />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 17 }} label="备注">
        {form.getFieldDecorator('remark', {
          initialValue: item.remark,
          rules: [{ required: true, message: '配置项描述！' }],
        })(<Input placeholder="请输入 remark" />)}
      </FormItem>
    </Modal>
  );
});

// 可编辑的列中的元素
class EditableCell extends PureComponent {
  getInput = () => {
    const { inputType } = this.props;
    if (inputType === 'number') {
      return <InputNumber />;
    }
    return <Input />;
  };

  render() {
    const { editing, dataIndex, title, inputType, record, index, ...restProps } = this.props;
    return (
      <EditableContext.Consumer>
        {form => {
          const { getFieldDecorator } = form;
          return (
            <td {...restProps}>
              {editing ? (
                <FormItem style={{ margin: 0 }}>
                  {getFieldDecorator(dataIndex, {
                    rules: [
                      {
                        required: true,
                        message: `请输入 ${title}!`,
                      },
                    ],
                    initialValue: record[dataIndex],
                  })(this.getInput())}
                </FormItem>
              ) : (
                restProps.children
              )}
            </td>
          );
        }}
      </EditableContext.Consumer>
    );
  }
}

/* eslint react/no-multi-comp:0 */
@connect(({ configItem, loading }) => ({
  configItem,
  loading: loading.models.configItem,
}))
// @Form.create() 是一个注解，就简化了xxx = Form.create(xxx);export xxx
@Form.create()
class ConfigItemList extends PureComponent {
  state = {
    addModalVisible: false,
    editModalVisible: false,
    editingId: '',
    item: {},
    pager: {
      pageNo: 1,
      pageSize: 10,
    },
  };

  columns = [
    {
      key: 'id',
      title: 'id',
      dataIndex: 'id',
      width: '10%',
    },
    {
      key: 'groupCode',
      title: '组code',
      dataIndex: 'groupCode',
      width: '20%',
    },
    {
      key: 'confKey',
      title: '配置key',
      dataIndex: 'confKey',
      editable: true,
      width: '34%',
    },
    {
      key: 'confValue',
      title: '配置值',
      dataIndex: 'confValue',
      editable: true,
      width: '34%',
    },
    {
      key: 'edit',
      title: '编辑',
      dataIndex: 'edit',
      width: '10%',
      render: (text, record) => (
        <span>
          <Button type="primary" icon="edit" onClick={() => this.showEditModal(record)} />
        </span>
      ),
    },
    {
      key: 'delete',
      title: '删除',
      dataIndex: 'delete',
      editable: false,
      width: '5%',
      render: (text, row) => (
        <span>
          <Button type="danger" icon="delete" onClick={() => this.showDeleteConfirm(row)} />
        </span>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    const {
      configItem: { searchParam },
    } = this.props;
    const { pager } = this.state;
    console.log('启动');

    this.setTableLoading();

    // 获取所有组code列表
    dispatch({
      type: 'configItem/fetchAllCodeList',
      payload: { searchParam },
    });

    // 获取组code列表
    dispatch({
      type: 'configItem/fetchCodeList',
      payload: { searchParam },
    });

    // 获取页面的总个数
    dispatch({
      type: 'configItem/getListCount',
      payload: { searchParam },
    });

    // 获取页面所有数据
    dispatch({
      type: 'configItem/getPageList',
      payload: { pager },
    });
  }

  expandedRowRender = record => (
    <div>
      <Row>
        <Col span={6}>
          <Badge status="success" text="组名称：" />
          <span>{record.groupCode}</span>
        </Col>
        <Col span={6}>
          <Badge status="success" text="创建时间：" />
          <span>{moment(record.createTime).format('YYYY-MM-DD HH:mm:ss')}</span>
        </Col>
        <Col span={6}>
          <Badge status="success" text="更新时间：" />
          <span>{moment(record.updateTime).format('YYYY-MM-DD HH:mm:ss')}</span>
        </Col>
      </Row>
      <br />
      <Row>
        <Col span={12}>
          <Badge status="success" text="备注：" />
          <span>{record.remark}</span>
        </Col>
      </Row>
    </div>
  );

  showDeleteConfirm = row => {
    const { dispatch } = this.props;
    console.log('点击');
    console.log(JSON.stringify(row));
    Modal.confirm({
      title: '确定要删除这条配置',
      okText: '确定删除',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        console.log('OK');
        dispatch({
          type: 'configItem/delete',
          payload: row.id,
        });
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  showAddModal = () => {
    this.setState({
      addModalVisible: true,
    });
  };

  hideAddModal = () => {
    this.setState({
      addModalVisible: false,
    });
  };

  editModal = () => {};

  showEditModal = record => {
    console.log('点击编辑');
    this.setState({
      item: record,
      editModalVisible: true,
    });
  };

  hideEditModal = () => {
    this.setState({
      editModalVisible: false,
    });
  };

  // 设置表格加载
  setTableLoading = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'configItem/setTableLoading',
    });
  };

  // 添加配置项
  handleAdd = fields => {
    const { dispatch } = this.props;
    const { pager } = this.state;
    this.setTableLoading();

    dispatch({
      type: 'configItem/add',
      payload: fields,
    });

    // 获取页面的总个数
    dispatch({
      type: 'configItem/getListCount',
      payload: '',
    });

    // 添加完之后刷新界面
    dispatch({
      type: 'configItem/getPageList',
      payload: { pager },
    });

    this.hideAddModal();
  };

  // 判断对象1是否包含对象2的所有属性
  contain = (object1, object2) => {
    let index = 0;
    const keys = Object.keys(object2);
    for (let i = 0; i < keys.length; i += 1) {
      const key = keys[i];
      if (object1[key] && object2[key] === object1[key]) {
        index += 1;
      }
    }
    return index === Object.keys(object2).length;
  };

  handleEdit = fields => {
    const { dispatch } = this.props;
    const { item } = this.state;
    this.setTableLoading();

    console.log('编辑修改');
    console.log(JSON.stringify(fields));
    console.log(JSON.stringify(item));

    // 判断是否有修改，如果没有修改，则不向后端发起更新
    if (!this.contain(item, fields)) {
      console.log('有变化需要修改');
      console.log(JSON.stringify(Object.assign(item, fields)));
      dispatch({
        type: 'configItem/update',
        payload: Object.assign(item, fields),
      });
    }

    this.hideEditModal();
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;
    const { pager } = this.state;

    console.log('启动查询');
    this.setTableLoading();

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      console.log('点击后的选项');
      console.log(JSON.stringify(fieldsValue));

      // 如果是全部则删除对应的选项
      /* eslint-disable no-param-reassign */
      if (fieldsValue !== undefined) {
        Object.keys(fieldsValue).forEach(key => {
          console.log(key, fieldsValue[key]);
          if (key === 'groupCode' && fieldsValue[key] === '_全部_') {
            delete fieldsValue.groupCode;
          }

          if (fieldsValue[key] === '') {
            delete fieldsValue[key];
          }
        });
      }
      /* eslint-disable no-param-reassign */

      console.log(JSON.stringify(fieldsValue));

      const values = {
        searchParam: fieldsValue,
        pager,
      };

      // 获取页面的总个数
      dispatch({
        type: 'configItem/getListCount',
        payload: values,
      });

      // 获取页面所有数据
      dispatch({
        type: 'configItem/getPageList',
        payload: values,
      });
    });
  };

  // 加载搜索输入框和搜索按钮
  renderSearchForm = () => {
    const {
      form: { getFieldDecorator },
    } = this.props;

    const {
      configItem: { groupCodeList },
    } = this.props;

    // console.log("加载groupCodeList")
    // console.log(JSON.stringify(groupCodeList));

    const options = groupCodeList.map(d => <Select.Option key={d.value}>{d.text}</Select.Option>);

    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={5} sm={24}>
            <FormItem label="配置组code">
              {getFieldDecorator('groupCode')(
                <Select
                  showSearch
                  placeholder="请选择配置组code"
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  {options}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={7} sm={24}>
            <FormItem label="配置key">
              {getFieldDecorator('confKey')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={7} sm={24}>
            <FormItem label="配置value">
              {getFieldDecorator('confValue')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={2} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
          <Col md={2} sm={24}>
            <Button icon="plus" type="primary" onClick={this.showAddModal}>
              新建
            </Button>
          </Col>
        </Row>
      </Form>
    );
  };

  edit = id => {
    console.log('key是什么');
    console.log(JSON.stringify(id));
    this.setState({ editingId: id });
  };

  isEditing = record => {
    const { editingId } = this.state;
    return record.id === editingId;
  };

  save = (form, record) => {
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      this.setTableLoading();

      const { dispatch } = this.props;
      dispatch({
        type: 'configItem/update',
        payload: Object.assign(record, row),
      }).then(() => {
        this.setState({ editingId: '' });
      });
    });
  };

  cancel = () => {
    this.setState({ editingId: '' });
  };

  onChange = (page, pageSize) => {
    const { dispatch } = this.props;
    const {
      configItem: { searchParam },
    } = this.props;

    const values = {
      searchParam,
      pager: {
        pageNo: page,
        pageSize,
      },
    };

    console.log('点击');
    console.log(JSON.stringify(searchParam));
    console.log(JSON.stringify(values));

    dispatch({
      type: 'configItem/getListCount',
      payload: { searchParam },
    });

    // 获取页面所有数据
    dispatch({
      type: 'configItem/getPageList',
      payload: values,
    });
  };

  render() {
    const {
      configItem: { tableList, tableLoading, totalNumber, pageNo, selectState, groupAllCodeList },
    } = this.props;

    // 替换表Table的组件
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };
    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: col.dataIndex === 'age' ? 'number' : 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: this.isEditing(record),
        }),
      };
    });
    const { addModalVisible, editModalVisible, item } = this.state;
    const parentAddMethods = {
      selectState,
      groupAllCodeList,
      handleAdd: this.handleAdd,
      hideAddModal: this.hideAddModal,
    };
    const parentEditMethods = {
      item,
      handleEdit: this.handleEdit,
      hideEditModal: this.hideEditModal,
    };

    return (
      <PageHeaderWrapper>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSearchForm()}</div>
            <div className={styles.tableListOperator} />
            <Table
              rowKey={record => record.id}
              components={components}
              dataSource={tableList}
              columns={columns}
              loading={tableLoading}
              pagination={false}
              expandedRowRender={this.expandedRowRender}
            />
            <br />
            <Pagination
              showQuickJumper
              onChange={this.onChange}
              defaultCurrent={1}
              current={pageNo}
              total={totalNumber}
            />
          </div>
        </Card>
        <CreateForm {...parentAddMethods} modalVisible={addModalVisible} />
        <EditForm {...parentEditMethods} modalVisible={editModalVisible} />
      </PageHeaderWrapper>
    );
  }
}

export default ConfigItemList;
